package com.hjy.search.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hjy.common.to.es.SkuEsModel;
import com.hjy.search.constant.EsConstant;
import com.hjy.search.service.MallSearchService;
import com.hjy.search.vo.SearchParams;
import com.hjy.search.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public SearchResult search(SearchParams searchParams) throws IOException {
        // 构造请求条件
        SearchRequest searchRequest = buildSearchRequest(searchParams);
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        // 构造响应条件
        return buildSearchResponse(response, searchParams);

    }

    private SearchRequest buildSearchRequest(SearchParams searchParams) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        // 构造请求条件
        /**
         * 模糊查询, 过滤 ,
         */
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (searchParams != null) {
            // must 查询
            if (StrUtil.isNotBlank(searchParams.getKeyword())) {
                boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", searchParams.getKeyword()));
            }
            // 过滤三级分类
            if (searchParams.getCatalog3Id() != null) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId", searchParams.getCatalog3Id()));
            }
            // 过滤品牌id
            if (CollUtil.isNotEmpty(searchParams.getBrandId())) {
                boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", searchParams.getBrandId()));
            }
            // 过滤属性
            if (CollUtil.isNotEmpty(searchParams.getAttrs())) {
                for (String attrStr : searchParams.getAttrs()) {
                    // 获取 id 和 属性值
                    String[] s = attrStr.split("_");
                    String attrId = s[0];
                    String[] attrValues = s[1].split(":");
                    BoolQueryBuilder nestedBoolQueryBuilder = QueryBuilders.boolQuery();
                    nestedBoolQueryBuilder.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                    nestedBoolQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                    // 构造条件
                    boolQueryBuilder.filter(QueryBuilders.nestedQuery("attrs", nestedBoolQueryBuilder, ScoreMode.None));
                }
            }
            // 是否有库存
            if (searchParams.getHasStock() != null) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", searchParams.getHasStock() == 1));

            }

            // 价格范围
            if (StrUtil.isNotBlank(searchParams.getSkuPrice())) {
                List<String> split = StrUtil.split(searchParams.getSkuPrice(), "_");
                if (split.size() >= 2) {
                    boolQueryBuilder.filter(QueryBuilders.rangeQuery("skuPrice").gte(split.get(0)).lte(split.get(1)));
                } else {
                    if (StrUtil.startWith(searchParams.getSkuPrice(), "_")) {
                        boolQueryBuilder.filter(QueryBuilders.rangeQuery("skuPrice").lte(split.get(0)));
                    }
                    if (StrUtil.endWith(searchParams.getSkuPrice(), "_")) {
                        boolQueryBuilder.filter(QueryBuilders.rangeQuery("skuPrice").gte(split.get(0)));
                    }
                }
            }
            searchSourceBuilder.query(boolQueryBuilder);

            /**
             * 排序, 分页, 高亮
             */
            // 排序
            if (StrUtil.isNotBlank(searchParams.getSort())) {
                String[] s = searchParams.getSort().split("_");
                searchSourceBuilder.sort(s[0], StrUtil.equalsIgnoreCase(s[1], "asc") ? SortOrder.ASC : SortOrder.DESC);
            }
            // 分页
            if (searchParams.getPageNum() != null) {
                searchSourceBuilder.from(EsConstant.PRODUCT_PAGE_SIZE * (searchParams.getPageNum() - 1));
                searchSourceBuilder.size(EsConstant.PRODUCT_PAGE_SIZE);
            }
            // 高亮
            if (StrUtil.isNotBlank(searchParams.getKeyword())) {
                HighlightBuilder highlightBuilder = new HighlightBuilder();
                highlightBuilder.field("skuTitle");
                highlightBuilder.preTags("<b style='color: red'>");
                highlightBuilder.postTags("</b>");
                searchSourceBuilder.highlighter(highlightBuilder);
            }


            /**
             * 聚合查询
             */
            // 1, 品牌聚合
            TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(10);
            // 品牌聚合的子聚合
            brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(10));
            brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(10));
            searchSourceBuilder.aggregation(brand_agg);
            // 2, 分类聚合
            TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(10);
            catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("brandName").size(10));
            searchSourceBuilder.aggregation(catalog_agg);
            // 3, 属性聚合
            NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
            TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(10);
            attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(50));
            attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
            attr_agg.subAggregation(attr_id_agg);
            searchSourceBuilder.aggregation(attr_agg);

            System.out.println("searchSourceBuilder构造条件 = " + searchSourceBuilder.toString());
            return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, searchSourceBuilder);
        }


        return null;

    }

    private SearchResult buildSearchResponse(SearchResponse response, SearchParams searchParams) {
        SearchHits hits = response.getHits();
        SearchResult searchResult = new SearchResult();
        // 1, 设置商品信息
        List<SkuEsModel> skuEsModels = new ArrayList<>();
        for (SearchHit hit : hits) {
            // 获取其json数据
            String sourceAsString = hit.getSourceAsString();
            SkuEsModel skuEsModel = JSONUtil.toBean(sourceAsString, SkuEsModel.class);
            if (StrUtil.isNotBlank(searchParams.getKeyword())) {
                HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                String string = skuTitle.getFragments()[0].string();
                skuEsModel.setSkuTitle(string);
            }
            skuEsModels.add(skuEsModel);
        }
        searchResult.setProduct(skuEsModels);
        // 2, 设置品牌信息
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            // 1, 品牌id
            String brandId = bucket.getKeyAsString();
            // 2, 品牌名称
            String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            // 3, 品牌图片
            String brandImg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            brandVo.setBrandId(Long.valueOf(brandId));
            brandVo.setBrandName(brandName);
            brandVo.setBrandImg(brandImg);
            brandVos.add(brandVo);
        }
        searchResult.setBrands(brandVos);
        // 3, 设置属性信息
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            // 1, 属性id
            String attrId = bucket.getKeyAsString();
            // 2, 属性名称
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            // 3, 属性值
            List<String> attrValues = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList());
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            attrVo.setAttrId(Long.valueOf(attrId));
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }
        searchResult.setAttrs(attrVos);

        // 4, 设置分类信息
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        for (Terms.Bucket bucket : catalog_agg.getBuckets()) {
            // 1, 分类id
            String catalogId = bucket.getKeyAsString();
            // 2, 分类名称
            String catalogName = ((ParsedStringTerms) bucket.getAggregations().get("catalog_name_agg")).getBuckets().get(0).getKeyAsString();
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            catalogVo.setCatalogId(Long.valueOf(catalogId));
            catalogVo.setCatalogName(catalogName);
            catalogVos.add(catalogVo);
        }
        searchResult.setCatalogs(catalogVos);

        // 5,当前页码 总记录数 总页码
        searchResult.setPageNum(searchParams.getPageNum());
        searchResult.setTotal(hits.getTotalHits().value);
        Integer total = (int) ((hits.getTotalHits().value + EsConstant.PRODUCT_PAGE_SIZE - 1) / EsConstant.PRODUCT_PAGE_SIZE);
        searchResult.setTotalPages(total);
        System.out.println("searchResult = " + JSONUtil.toJsonStr(searchResult));

        // 6. 页码
        ArrayList<Integer> integers = new ArrayList<>();
        for (int i = 1; i <= total; i++) {
            integers.add(i);
        }
        searchResult.setPageNavs(integers);
        return searchResult;
    }
}
